<?php

namespace App\Kuafu\Export\Service;

use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Export\Jobs\QueueExport;
use App\Kuafu\Export\Model\ExportDownloadModel;
use App\Kuafu\Order\Enum\OrderMerchantEnum;
use Kuafu\File\FileUtil;

class ExportDownloadService extends BaseService
{
    public static function lists(int $client, int $userId, int $pageSize, int $pageNum): array
    {
        $paginator = ExportDownloadModel::query()
                                        ->with('userRel')
                                        ->where('createdByUid', $userId)
                                        ->where('client', $client)
                                        ->where('expireTime', '>', time())
                                        ->orderByDesc('id')
                                        ->paginate($pageSize, ['*'], 'page', $pageNum);

        return self::pageLists($paginator, function ($item) {

            // 更新时间
            $updateTime = $item->completeTime ?: $item->updatedAt->timestamp;

            if (in_array($item->fileType, [
                ExportDownloadModel::FILE_TYPE_WEB_TIGER_WORK_ORDER,
                ExportDownloadModel::FILE_TYPE_WEB_TIGER_APPRAISE,
                ExportDownloadModel::FILE_TYPE_WEB_ALBUM_RESOURCE,
                ExportDownloadModel::FILE_TYPE_WEB_ARTICLE_HOLISTIC_ANALYSIS,
                ExportDownloadModel::FILE_TYPE_WEB_ARTICLE_SINGLE_ANALYSIS,
                ExportDownloadModel::FILE_TYPE_WEB_CATEGORY_SINGLE_ANALYSIS,
                ExportDownloadModel::FILE_TYPE_WEB_CATEGORY_HOLISTIC_ANALYSIS,
            ])) {
                $pathStr = $item['path'];
            } else {
                // 文件名urlencode处理
                $pathArr                      = explode('/', $item['path']);
                $pathArr[count($pathArr) - 1] = urlencode($pathArr[count($pathArr) - 1]);
                $pathStr                      = implode('/', $pathArr);
            }

            return [
                'id'              => $item['id'],
                'name'            => $item['name'],
                'url'             => FileUtil::domain() . '/' . $pathStr,
                'createdUsername' => $item->userRel->username ?? '',
                'createdAt'       => date('Y-m-d H:i:s', $item->createdAt->timestamp),
                'updatedAt'       => date('Y-m-d H:i:s', $updateTime),
                'status'          => $item->status,
                'statusText'      => ExportDownloadModel::STATUS_TEXT[$item->status] ?? '',
                'fileType'        => $item->fileType,
                'fileTypeText'    => $item->fileTypeTextDefine,
                'ext'             => $item->ext,// 文件扩展名
            ];
        });
    }

    public static function export(
        int $client,
        int $fileType,
        int $shopId,
        int $showTimeTab,
        int $showStartAt,
        int $showEndAt,
        array $shopIds = [],
        array $otherParams = []
    ) {

        // 时间获取
        $timeObj = OrderMerchantEnum::getIns()
                                    ->setShowTimeTab($showTimeTab, $showStartAt, $showEndAt)
                                    ->getShowTimeTab();

        $showStartAt = $timeObj[1];
        $showEndAt   = $timeObj[2];

        $params = [
            'shopId'      => $shopId,
            'shopIds'     => $shopIds,
            'showTimeTab' => $showTimeTab,
            'showStartAt' => $showStartAt,
            'showEndAt'   => $showEndAt,
            'otherParams' => $otherParams,
        ];

        $fileName = '';

        if (isset($otherParams['fileName'])) {
            $fileName = $otherParams['fileName'];
        }

        $export = (new ExportDownloadModel)->add($client, $fileType, $params, $fileName);

        dispatch(new QueueExport($export->id))->onQueue(QueueExport::QUEUE_NAME);
    }

    /**
     * 其他项目导出创建处理
     * @param int $client
     * @param int $fileType
     * @param array $params
     * @param string $name
     * @param int $createdByUid
     * @return array
     */
    public static function remoteExportAdd(
        int $client,
        int $fileType,
        array $params,
        string $name,
        int $createdByUid
    ): array
    {
        $export = (new ExportDownloadModel)->add($client, $fileType, $params, $name, $createdByUid);
        return ['id' => $export->id];
    }

    /**
     * 其他项目导出完成处理
     * @param $id
     * @param string $path
     * @return array
     */
    public static function remoteExportFinish($id, $path = ''): array
    {
        $export = ExportDownloadModel::query()->find($id);
        if ($export) {
            if ($path) {
                // 导出完成
                $export->finish($path);

                // 发送飞书通知
                ExportDownloadModel::sendFs($export, $path);
            } else {
                // 导出异常
                $export->dealError();
            }
        }
        return [];
    }
}
